package cn.fx.filters;

import com.alibaba.fastjson.JSONObject;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.util.HashMap;

@Component
public class LoginCheckFilter extends ZuulFilter {

    //当前自定义过滤器在什么时候执行，在前置过滤器执行
    @Override
    public String filterType() {
        return "pre";
    }

    //filter执行时机，数字越小越先执行，不建议负数，最小为0
    @Override
    public int filterOrder() {
        return 0;
    }

    //此方法用来判断是否需要执行目标业务方法的，如：登录校验就是判断当前请求是否需要校验
    @Override
    public boolean shouldFilter() {
        // 得到上下文对象
        RequestContext currentContext = RequestContext.getCurrentContext();
        // 得到当前请求的uri
        String uri = currentContext.getRequest().getRemoteUser();
        //判断是否包含login/register
        return !StringUtils.endsWithIgnoreCase(uri, "login") && !StringUtils.endsWithIgnoreCase(uri, "register");
    }

    //执行目标业务方法，是否调用取决于shouldFilter的返回值是否为true
    @Override
    public Object run() throws ZuulException {

        //得到token
        String token = RequestContext.getCurrentContext().getRequest().getHeader("token");
        HttpServletResponse response = RequestContext.getCurrentContext().getResponse();

        // 设置响应数据的格式和编码
        response.setContentType("application/json;charset=utf-8");

        //判断tokentoken是否为null
        if (StringUtils.isEmpty(token)){
            try {
                //准备一个map
                HashMap<String, Object> map = new HashMap<>();
                map.put("success",false);
                map.put("message","nologin");
                PrintWriter writer = response.getWriter();

                //利用fastjson转换map对象
                String strJson = JSONObject.toJSONString(map);
                writer.write(strJson);

                //阻止后续filter执行
                RequestContext.getCurrentContext().setSendZuulResponse(false);
            } catch(Exception e) {
                e.printStackTrace();

            }
        }
        //如果想要放行，此处随意返回
        return null;
    }
}
